"""Header_Information
------------------------------------
    File_Name: login
    Author: RR9
    Date: 2024/10/19
    Description: 
------------------------------------
"""
from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from starlette import status
from tortoise.exceptions import DoesNotExist
from app.utils.jwt import create_access_token, authenticate_user, verify_token
from app.models.user import User
from app.schemas.login import Token
from loguru import logger

log = logger.bind(module="app")

router = APIRouter()


@router.post("/token", summary="生成token")
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()) -> Token:
    """生成token
    校验用户信息并生成token
    OAuth2PasswordRequestForm：grant_type,username,password,scope,client_id,client_secret
    :param form_data:
    :return:
    """
    # ⚠️：因属性原因，使用username代替数据库中userid
    userid = form_data.username  # userid
    password = form_data.password
    try:
        db_user = await User.get(userid=userid).values('userid', 'username', 'hashed_password', 'disabled')
    except DoesNotExist:
        db_user = None
    except Exception as e:
        log.info(str(e))
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    user = authenticate_user(db_user, password)

    if not user:
        log.info("无效的用户名或密码")
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="无效的用户名或密码",
            headers={"WWW-Authenticate": "Bearer"}
        )
    elif user.disabled:
        log.info("用户状态不可用")
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户状态不可用",
            headers={"WWW-Authenticate": "Bearer"}
        )
    access_token = create_access_token(
        data={"userid": userid, "username": user.username}
    )
    return Token(access_token=access_token, token_type="bearer")


@router.post("/t1", summary='测试1')
async def get_user(user: User = Depends(verify_token)):
    log.info('log.get_user')
    return user
